import '../../scss/app.scss'
import React from 'react'
import Http from '../../components/Http'
import {Table,Icon,Button,Form,Select,Input,message, Divider} from 'antd'
import Fragment from '../../components/Fragment'
import {FormReceiver} from '../../utils/FormReceiver'
import ReactDOM from "react-dom";
import MenuValidator from '../../validator/menu'
import Validator from '../../validator/index'
import {post} from '../../utils/http'
import {add_menu, edit_menu, del_menu} from '../../api'
import connect from 'react-redux/es/connect/connect'
import {authAction} from '../../actions/auth'
import configStore from '../../store'
import {authReducer} from "../../reducers/auth";
import {loginReducer} from "../../reducers/login";
import Provider from "react-redux/es/components/Provider";


const columns = [{
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    render: (text) => (
        <span dangerouslySetInnerHTML={{__html:text}}></span>
    )
},{
    title: '图标',
    dataIndex: 'icon',
    key: 'icon',
    render: icon => <Icon type={icon}/>
},{
    title: '规则',
    dataIndex: 'rule',
    key: 'rule'
},{
    title: '参数',
    dataIndex: 'data',
    key: 'data'
},{
    title: '备注',
    dataIndex: 'remark',
    key: 'remark'
},{
    title: '排序',
    dataIndex: 'sort',
    key: 'sort'
},{
    title: '操作',
    key: 'action',
    render: (text, record) => (
        <span>

        </span>
    )
}]
@Http(
    { url:'/api/list' },
    (res) => {
        if(res.code === 0 || res.code === '0'){
            return {dataSource: res.data.menus}
        }else {
            alert(res.msg)
        }
    },
    <Table columns={columns} dataSource={[]}/>
)
class MenuTable extends React.Component{
    render(){
        let {dataSource, authButton} = this.props
        return <Table dataSource={dataSource}>
            <Table.Column title="名称"
                    dataIndex="name"
                    key= "name"
                    render={(text) => (
                        <span dangerouslySetInnerHTML={{__html:text}}></span>
                    )}/>
            <Table.Column title="图标"
                    dataIndex="icon"
                    key="icon"
                    render={(text) => <Icon type={text}/> }/>
            <Table.Column title="规则"
                    dataIndex="rule"
                    key="rule"/>
            <Table.Column title="参数"
                    dataIndex="data"
                    key="data"/>
            <Table.Column title="备注"
                    dataIndex="remark"
                    key="remark"/>
            <Table.Column title="排序"
                    dataIndex="sort"
                    key="sort"/>
            <Table.Column title="操作"
                    key="action"
                    render={(text, record) => (
                        <span>
                            <Icon type="edit" onClick={() => {this.props.onEditMenu(record)}}/>
                            <Icon type="close" onClick={() => {this.props.onDelMenu(record)}}/>
                        </span>
                    )}/>
        </Table>
    }
}

@Fragment('sys/menu')
class App extends React.Component{
    constructor(props) {
        super(props)
        this.onNewMenu = this.onNewMenu.bind(this)
        this.editMenu = this.editMenu.bind(this)
        this.delMenu = this.delMenu.bind(this)
    }
    componentDidMount(){
        this.props.authAction('/menu')
    }
    editMenu(record) {
        let dataSource = this.refs.menuTables.getHttpData().dataSource
        let options = dataSource.map(item => <Select.Option value={item.id}><span dangerouslySetInnerHTML={{__html:item.name}}></span></Select.Option>),
            formItemLayout = {
                labelCol: {span: 4},
                wrapperCol: {span: 16}
            }
        let top = <Select.Option value = "0">顶级菜单</Select.Option>
        record = {...record}
        record.name = record.name.replace(/&nbsp;/g,'').replace(/_/g, '').replace(/\|/g, '')
        let form = (
            <Form>
                <Form.Item label="上级菜单" {...formItemLayout}>
                    <Select showSearch placeholder="请选择上级菜单"
                            optionFilterProp = "children"
                            filterOption = {(input, option) => option.props.children.props.dangerouslySetInnerHTML.__html.indexOf(input) >= 0}
                            onChange={FormReceiver('pid', record)}
                            defaultValue={`${record.pid}`}
                    >
                        {[top,...options]}
                    </Select>
                </Form.Item>
                <Form.Item label="名称" {...formItemLayout}>
                    <Input placeholder="名称" onChange={FormReceiver('name',record)} defaultValue = {record.name}/>
                </Form.Item>
                <Form.Item label="规则" {...formItemLayout}>
                    <Input placeholder="规则" onChange={FormReceiver('rule', record)} defaultValue = {record.rule}/>
                </Form.Item>
                <Form.Item label="参数" {...formItemLayout}>
                    <Input placeholder="参数" onChange={FormReceiver('data', record)} defaultValue = {record.data}/>
                </Form.Item>
                <Form.Item label="类型" {...formItemLayout}>
                    <Select placeholder="请选择类型" onChange={FormReceiver('type', record)} defaultValue = {`${record.type}`}>
                        <Select.Option value = "1">菜单</Select.Option>
                        <Select.Option value = "2">按钮</Select.Option>
                        <Select.Option value = "3">接口</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label="状态" {...formItemLayout}>
                    <Select placeholder="请选择状态" onChange={FormReceiver('status', record)} defaultValue = {`${record.status}`}>
                        <Select.Option value = "1">启用</Select.Option>
                        <Select.Option value = "2">禁用</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label="排序" {...formItemLayout}>
                    <Input placeholder="排序" onChange={FormReceiver('sort', record)} defaultValue = {record.sort}/>
                </Form.Item>
                <Form.Item label="备注" {...formItemLayout}>
                    <Input type="textarea" placeholder="备注"  onChange={FormReceiver('remark', record)} defaultValue = {record.remark}/>
                </Form.Item>
            </Form>
        )
        this.context.modal(
            form,
            '编辑菜单',
            async () => {
                let validator = new Validator(MenuValidator)
                let res = await validator.check(record)
                if(res !== true) {
                    message.error(res)
                    return false
                }
                try{
                    let params = {...record}
                    params.childs = undefined
                    let data = await post(edit_menu, params)
                    message.info(data.msg)
                    this.refs.menuTables.reload()
                    return true
                }catch(err){
                    if(err.type === 1) {
                        message.error(err.error)
                        return false
                    }
                }
            }
        )

    }
    async delMenu(record) {
        try{
            let data = await post(del_menu, {id:record.id})
            message.info(data.msg)
            this.refs.menuTables.reload()
        }catch(err) {
            if(err.type === 1) {
                message.error(err.error)
            }
        }
    }
    onNewMenu(e) {
        let dataSource = this.refs.menuTables.getHttpData().dataSource
        let options = dataSource.map(item => <Select.Option value={item.id}><span dangerouslySetInnerHTML={{__html:item.name}}></span></Select.Option>),
            formItemLayout = {
                labelCol: { span: 4 },
                wrapperCol: { span: 16 },
            },
            formData = {}
        let top = <Select.Option value = "0">顶级菜单</Select.Option>
        let form = (
            <Form>
                <Form.Item label="上级菜单" {...formItemLayout}>
                    <Select showSearch placeholder="请选择上级菜单"
                            optionFilterProp = "children"
                            filterOption={(input, option) => option.props.children.props.dangerouslySetInnerHTML.__html.indexOf(input) >= 0}
                            onChange = {FormReceiver('pid', formData)}>
                        {[top, ...options]}
                    </Select>
                </Form.Item>
                <Form.Item label="名称" {...formItemLayout}>
                    <Input placeholder = "名称" onChange={FormReceiver('name', formData)}/>
                </Form.Item>
                <Form.Item label="规则" {...formItemLayout}>
                    <Input placeholder = "规则" onChange={FormReceiver('rule', formData)}/>
                </Form.Item>
                <Form.Item label="参数" {...formItemLayout}>
                    <Input placeholder="参数" onChange={FormReceiver('data', formData)}/>
                </Form.Item>
                <Form.Item label="类型" {...formItemLayout}>
                    <Select placeholder="请选择类型" onChange={FormReceiver('type', formData)}>
                        <Select.Option value = "1">菜单</Select.Option>
                        <Select.Option value = "2">按钮</Select.Option>
                        <Select.Option value = "3">接口</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label="状态" {...formItemLayout}>
                    <Select placeholder="请选择状态" onChange={FormReceiver('status', formData)}>
                        <Select.Option value = "1">启用</Select.Option>
                        <Select.Option value = "2">禁用</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label = "排序" {...formItemLayout}>
                    <Input placeholder="排序" onChange={FormReceiver('sort', formData)}/>
                </Form.Item>
                <Form.Item label="备注" {...formItemLayout} >
                    <Input type = "textarea" placeholder="备注" onChange={FormReceiver('remark', formData)}/>
                </Form.Item>
            </Form>
        )
        this.context.modal(
            form,
            '新增菜单',
            async () =>{
                let validator = new Validator(MenuValidator)
                let res = await validator.check(formData)
                if(res !== true) {
                    message.error(res)
                    return false
                }
                //发送数据到服务端
                try{
                    let data = await post(add_menu, formData)
                    message.info(data.msg)
                    this.refs.menuTables.reload()
                    return true
                }catch(err){
                    if(err.type === 1) {
                        message.error(err.error)
                        return false
                    }
                }
            });
    }
    render() {
        let {isloading, buttons} = this.props
        if(isloading){
            return (
                <div class = "full-screen">
                  <div className="app-operation">
                    <Button onClick={this.onNewMenu}>新增</Button>
                  </div>
                  <MenuTable  ref="menuTables"/>
                </div>

            )
        }else {
            return (
                <div className="full-screen">
                  <div className="app-operation">
                    <Button onClick={this.onNewMenu}>新增</Button>
                  </div>
                  <MenuTable
                    ref="menuTables"
                    authButtons={buttons}
                    onEditMenu={this.editMenu}
                    onDelMenu={this.delMenu}
                  />
                </div>
            )
        }

    }
}

const Page = connect(
    state => ({isloading:state.isloading,errMsg: state.errMsg}),
    {authAction}
)(App)

let store = configStore(loginReducer)
ReactDOM.render(
    <Provider store={store}><Page/></Provider>,
    document.getElementById('root')
)
